<template>
  <div class="contianer">
    <el-form
      :model="tableData"
      :rules="rules"
      ref="tableData"
      label-width="100px"
      class="demo-ruleForm"
    >
      <table>
        <tr>
          <td colspan="2">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="tableData.title" placeholder="请输入标题"></el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <el-form-item label="正文内容" prop="content">
              <quill-editor
                class="editor"
                v-model="tableData.content"
                ref="content"
                :options="editorOption"
                @change="onEditorChange($event)"
              >
              </quill-editor>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <el-form-item label="文章标签">
              <div class="block">
                <el-cascader
                  placeholder="点击添加标签"
                  :options="options"
                  :props="{ multiple: true }"
                  v-model="tagList"
                  :show-all-levels="false"
                  id="tagList"
                  clearable
                  filterable
                ></el-cascader>
              </div>
              <!-- <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false"
                @close="handleClose(tag)">
                {{ tag }}
              </el-tag>
              <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
                @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button> -->
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td style="width: 25%">
            <el-form-item label="文章封面" id="coverForm">
              <el-upload
                action="api/util/uploadImg"
                list-type="picture-card"
                :auto-upload="true"
                :headers="MyHeader"
                :on-change="handleExceed"
                :file-list="fileList"
                :limit="1"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                name="imgFile"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail" :src="tableData.fileUid" />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <!-- <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                      <i class="el-icon-download"></i>
                    </span> -->
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </td>
          <td style="width: 75%">
            <el-form-item label="文章摘要" id="summary">
              <el-input
                v-model="tableData.summary"
                placeholder="文章摘要"
                type="textarea"
                id="summaryInput"
              ></el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <el-form-item label="是否原创">
              <!-- <el-radio-group v-model="tableData.isOriginal">
                <el-radio :label="1">原创</el-radio>
                <el-radio :label="2">转载</el-radio>
              </el-radio-group> -->
              <el-radio-group v-model="tableData.isOriginal">
                <el-radio-button label="原创"></el-radio-button>
                <el-radio-button label="转载"></el-radio-button>
              </el-radio-group>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <div class="formButton">
              <!-- <el-form-item style="float: right;">
                <el-button type="danger" @click="resetForm('tableData')" round>重置内容</el-button>
                <el-button type="success" @click="lookForm()" round>预览</el-button>
                <el-button type="primary" @click="submitForm()" id="submitDiv" round>立即发布</el-button>
              </el-form-item> -->
            </div>
          </td>
        </tr>
      </table>
    </el-form>

    <div class="sendBogBtn">
      <el-button type="danger" @click="resetForm('tableData')" round>重置内容</el-button>
      <el-button type="success" @click="lookForm()" round>预览</el-button>
      <el-button type="primary" @click="submitForm()" id="submitDiv" round
        >立即发布</el-button
      >
    </div>
  </div>
</template>

<script>
import { quillEditor, Quill } from "vue-quill-editor";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
Quill.register("modules/ImageExtend", ImageExtend);
import { $addArticle } from "@/assets/api/user.js";
import { $deleteUploadImg } from "@/assets/api/user.js";
import { $findBolgTag } from "@/assets/api/user.js";
export default {
  name: "addArticle",
  data() {
    return {
      MyHeader: { token: JSON.parse(sessionStorage.getItem("token")) },
      tableData: {
        id: "", //id标识
        title: "", //博客标题
        summary: "", //博客简介
        content: "", //博客内容
        tagUid: "", //标签uid
        clickCount: 0, //博客点击数
        collectCount: 0, //博客收藏数
        fileUid: "", //标题图片uid
        createdTime: "", //创建时间
        modifiedTime: "", //更新时间
        isOriginal: "原创", //原创
        author: "", //作者
        articlesPart: "", //文章出处
        openComment: "", //是否开启评论
      },
      editorOption: {
        placeholder: "此处输入赛事规程",
        modules: {
          ImageExtend: {
            loading: true,
            name: "imgFile", //图片参数名
            size: 1, // 可选参数 图片大小，单位为M，1M = 1024kb
            action: "api/util/uploadImg", //上传的服务器地址，如果action为空，则采用base64插入图片
            // response 为一个函数，用来获取服务器返回的具体图片地址
            response: (res) => {
              console.log(res);
              const imgUrl = res.data.resPath;
              return imgUrl;
            },
            headers: (xhr) => {
              // 上传图片请求需要携带token的 在xhr.setRequestHeader中设置，这里我的token存放在sessionStorage中
              xhr.setRequestHeader("token", JSON.parse(sessionStorage.getItem("token")));
            },
            // 可选参数 设置请求头部
            sizeError: () => {}, // 图片超过大小的回调
            start: () => {}, // 可选参数 自定义开始上传触发事件
            end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
            error: () => {}, // 可选参数 上传失败触发的事件
            success: () => {
              console.log("ImageExtend中的success：上传成功");
            }, // 可选参数  上传成功触发的事件
            change: (xhr, formData) => {
              // xhr.setRequestHeader('myHeader','myValue')
              // formData.append('token', 'myToken')
            }, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
          },
          // 如果不上传图片到服务器，此处不必配置
          toolbar: {
            // container为工具栏，此次引入了全部工具栏，也可自行配置
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ script: "sub" }, { script: "super" }],
              [{ indent: "-1" }, { indent: "+1" }],
              [{ direction: "rtl" }],
              [{ size: ["small", false, "large", "huge"] }],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ color: [] }, { background: [] }],
              [{ font: [] }],
              [{ align: [] }],
              ["image"],
            ],
            // 上传成功，回显图片（会进入如上面ImageExtend的各过程，返回<img src="http://xx.xx.xx.xx:xxxx/file/xxx.jpg">）
            handlers: {
              image: function () {
                // 劫持原来的图片点击按钮事件
                QuillWatch.emit(this.quill.id);
              },
            },
          },
        },
      },
      uploadFiles: [],
      fileList: [],
      editForm: {
        chairImg: "",
      }, //图片上传成功后返回的路径，用户回调函数

      //标签
      // dynamicTags: [],
      // inputVisible: false,
      // inputValue: '',

      tagList: [],

      options: [
        {
          value: "类型",
          label: "类型",
          children: [],
        },
      ],

      //封面属性
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,

      //表单规则
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" },
        ],
        content: [{ required: true, message: "请输入文章内容", trigger: "blur" }],
      },
    };
  },
  created() {
    this.findBolgTag();
  },
  methods: {
    findBolgTag() {
      $findBolgTag().then((res) => {
        if (res.data.success) {
          this.options = res.data.data.findBolgTag;
        } else {
          this.message(res);
        }
      });
    },
    //提交方法
    submitForm() {
      var tagArr = [];
      for (var i = 0; i < this.tagList.length; i++) {
        tagArr[i] = this.tagList[i][1];
      }

      this.tableData.isOriginal = this.tableData.isOriginal == "原创" ? "1" : "0";
      $addArticle({ wqunBlog: this.tableData, tagArr: tagArr }).then((res) => {
        this.message(res);
        if (res.data.success) {
          (this.tableData = []), (this.tagList = []), (this.editForm = []);
        }
      });
    },
    onEditorChange(e) {
      // console.log('onEditorChange打印e')
      // console.log(e)
    },

    //图片上传
    handleAvatarSuccess(res) {
      if (res.success) {
        this.tableData.fileUid = res.data.resPath;
        this.$message({
          type: "success",
          message: "",
        });
      } else {
        this.$message({
          type: "error",
        });
      }
    },
    beforeAvatarUpload(file) {
      // 设置限定格式
      const img_mimetype = ["image/jpeg", "image/jpg", "image/png"];
      const isJPG = img_mimetype.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("上传头像只能是图片格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
        return false;
      }
      return isJPG && isLt2M;
    },
    // 提交修改的表单数据
    // editChairmans() {
    //   const { data: rese } = this.$axios.post('api/blog/uploadimg', this.editForm);
    // },

    //封面方法
    handleRemove(file) {
      //移除图片
      $deleteUploadImg({ oosImgPath: this.tableData.fileUid }).then((res) => {
        if (res.data.success) {
          this.fileList = [];
          if (this.fileList.length >= 1) {
            this.getstyle(".el-upload--picture-card").display = "none";
          } else {
            setTimeout(() => {
              this.getstyle(".el-upload--picture-card").display = "inline-block";
            }, 1150);
          }
          this.$message({ type: "success" });
        } else {
          this.$message({ type: "error" });
        }
      });
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    getNowTime() {
      let now = new Date();
      let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
      let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
      let today = now.getDate(); //获取当前日(1-31)
      let hour = now.getHours(); //获取当前小时数(0-23)
      let minute = now.getMinutes(); //获取当前分钟数(0-59)
      let second = now.getSeconds(); //获取当前秒数(0-59)
      let nowTime = "";
      nowTime =
        year + "-" + month + "-" + today + " " + hour + ":" + minute + ":" + second;
      return nowTime;
    },
    resetForm(formName) {
      this.$confirm("是否清空该文章编辑?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$refs[formName].resetFields();
          this.tableData = [];
          this.tagList = [];
          this.editForm = [];
          this.$message({
            type: "success",
            message: "已清空",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
      // if(confirm("是否清空该文章编辑？")){
      //   this.$refs[formName].resetFields();
      // }
    },

    // handleDownload(file) {
    //   console.log(file);
    // },
    getstyle(sname) {
      //从整个页面查找class为sname的页面
      for (var i = 0; i < document.styleSheets.length; i++) {
        var rules;
        if (document.styleSheets[i].cssRules) {
          rules = document.styleSheets[i].cssRules;
        } else {
          rules = document.styleSheets[i].rules;
        }
        for (var j = 0; j < rules.length; j++) {
          if (rules[j].selectorText == sname) {
            return rules[j].style;
          }
        }
      }
    },

    handleExceed(files, fileList) {
      this.fileList = fileList;
      if (this.fileList.length >= 1) {
        this.getstyle(".el-upload--picture-card").display = "none";
      } else {
        this.getstyle(".el-upload--picture-card").display = "inline-block";
      }
    },

    //事件
    addArticle() {},
    onEditorBlur() {},
    onEditorFocus() {
      //获得焦点事件
    },

    //传输图片添加
    // Vue.prototype.hostURL = 'http://localhost:8081/static/'

    imgUrlToBase64(url) {
      return new Promise((resolve, reject) => {
        if (!url) {
          reject("请传入url内容");
        }
        // 图片地址
        const image = new Image();
        // 设置跨域问题
        image.setAttribute("crossOrigin", "anonymous");
        // 图片地址
        image.src = url;
        image.onload = () => {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");
          canvas.width = image.width;
          canvas.height = image.height;
          ctx.drawImage(image, 0, 0, image.width, image.height);
          // 获取图片后缀
          const ext = url.substring(url.lastIndexOf(".") + 1).toLowerCase();
          // 转base64
          const dataUrl = canvas.toDataURL(`image/${ext}`);
          resolve(dataUrl || "");
        };
      });
    },

    //预览
    lookForm() {
      //将信息缓存到浏览器里面
      console.log(this.tableData);
      this.tableData.createdTime = this.getNowTime();
      var arr = JSON.stringify(this.tableData);
      window.localStorage.setItem("formData", arr);

      //将封面信息传给预览界面fileList
      var fileList = JSON.stringify(this.fileList);
      window.localStorage.setItem("fileList", fileList);

      console.log(this.fileList);

      //标签组
      var tag = JSON.stringify(this.tagList);
      window.localStorage.setItem("tagList", tag);
      this.$router.push({
        name: "previewArticle",
      });
    },
  },
};
</script>

<style scoped>
.sendBogBtn {
  margin-left: 60%;
}
.contianer {
  height: 89%;
  padding-bottom: 40px;
}

.demo-ruleForm {
  padding-right: 30px;
  width: 1000px;
  margin-top: 30px;
  margin-left: 15%;
  overflow-y: scroll;
  height: 100%;
}

#coverForm {
  display: inline-block;
  height: 150px;
  width: 25%;
}

#summary {
  display: inline-block;
  margin-left: 5%;
  width: 95%;
  height: 150px;
}

#summaryInput {
  height: 150px;
}

#tagList {
  min-width: 500px;
}

.formButton {
  bottom: 0px;
  min-width: 900px;
}
</style>

<style>
.ql-editor {
  min-height: 300px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
